#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Justin

import numpy as np
from skimage import io, filters, color, morphology, feature, measure, segmentation
from skimage.morphology import square
from PIL import ImageDraw
from src.acquisition.slice.patches import parameter as pr

def get_roi(src_img,map_txt_path = None,if_write_txt=False):
    img = color.rgb2hsv(src_img)
    # mask = np.ones(img.Shape, dtype=np.uint8)
    # **************原来的HE切片阈值处理*******************
    # mask1 = (img[:, :, 2] < 0.9) & (img[:, :, 2] > 0.15)
    # mask2 = (img[:, :, 1] < 0.9) & (img[:, :, 1] > 0.10)
    # mask3 = (img[:, :, 0] < 0.9) & (img[:, :, 0] > 0.10)
    # result = mask1 & mask2 & mask3
    # # 开运算和闭运算（后一个参数用于设定局部区域的形状和大小）
    # # 前者消除小物体，后者消除小黑洞
    # result = morphology.binary_opening(result, square(20))
    # result = morphology.binary_closing(result, square(5))
    # **************原来的HE切片阈值处理*******************

    # **************后来的HER2切片阈值处理*******************
    mask1 = (img[:, :, 2] < 0.99) & (img[:, :, 2] > 0)
    mask2 = (img[:, :, 1] < 0.99) & (img[:, :, 1] > 0)
    mask3 = (img[:, :, 0] < 0.99) & (img[:, :, 0] > 0)
    result = mask1 & mask2 & mask3

    # 开运算和闭运算（后一个参数用于设定局部区域的形状和大小）
    # 前者消除小物体，后者消除小黑洞
    result = morphology.binary_opening(result, square(20))
    result = morphology.binary_closing(result, square(5))

    result = np.logical_not(result)

    # **************后来的HER2切片阈值处理*******************

    # **************输出整张图片非白色区域的坐标*******************
    if if_write_txt:
        output_path = map_txt_path
        export_original_roi_in_txt(result,output_path)
    # **************输出整张图片非白色区域的坐标*******************
    return result

# 这里貌似是再对之前的二值图像做腐蚀留边处理后，返回不为0的点，并对这些点做“数值运算，并返回”
# 这里的distance是全局参数中的EXTRACT_PATCH_DIST，不知道什么意思？？？
def get_seeds(src_img, distance):
    patch_size = pr.PATCH_SIZE_LOW
    seed_img = morphology.binary_erosion(src_img, square(patch_size))#灰度图像腐蚀，图像中物体会收缩/细化：https://wenku.baidu.com/view/c600c8d1360cba1aa811da73.html
    seed_img = morphology.binary_erosion(seed_img, square(8))  # 留边

    space_patch = distance
    # pos对应的应该是seed_img中不为0的坐标（01应该代表YX）
    pos = seed_img.nonzero()
    # 不知道这部对点的处理是为了什么？？？？
    y = (np.rint(pos[0] / space_patch + 0.5) * space_patch).astype(np.int32)  # row
    x = (np.rint(pos[1] / space_patch + 0.5) * space_patch).astype(np.int32)  # col

    result = set()
    for xx, yy in zip(x, y):
        result.add((xx, yy))

    return result


def draw_seeds(src_img, seeds, patch_size):
    draw = ImageDraw.Draw(src_img)
    half = patch_size / 2
    for (x, y) in seeds:
        draw.rectangle([x - half, y - half, x + half, y + half], outline='red')
    return src_img


# 自己加的一段代码
# 用于输出开闭运算后的roi图片在缩略图上对应的x,y坐标点
def export_original_roi_in_txt(result,output_path):
    # pos[1]应该是宽，pos[0]应该是高
    pos = result.nonzero()
    line_number = len(pos[0])
    txt_file = open(output_path, 'w')
    # random = np.random.RandomState(0)  # RandomState生成随机数种子

    for i in range(line_number):
        txt_file.write(str(pos[1][i])+','+str(pos[0][i])+'\n')
    txt_file.close()

    # **************输出整张图片非白色区域的坐标*******************